package net.csdra.libraryborrowing.service.book;

import net.csdra.libraryborrowing.domain.book.BookCopy;
import net.csdra.libraryborrowing.domain.book.BookCopyLog;
import net.csdra.libraryborrowing.domain.book.BookCopyRepository;
import net.csdra.libraryborrowing.domain.book.BookCopyState;
import net.csdra.libraryborrowing.service.user.CurrentUserInfo;
import net.csdra.libraryborrowing.util.Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.nio.file.AccessDeniedException;

/**
 * Created by xiaomi on 2017/10/16.
 */
@Service
public class BookCopyManageServiceImpl implements BookCopyManageService {

    @Autowired
    BookCopyRepository bookCopyRepository;
    @Autowired
    CurrentUserInfo currentUserInfo;
    @Autowired
    BookCopyLogComponent bookCopyLogComponent;

    @Override
    @Transactional
    public BookCopy updateBookCopy(UpdateBookCopy updateBookCopy) throws AccessDeniedException {
        BookCopy bookCopy = bookCopyRepository.findOne(updateBookCopy.getBookCopyId());
        Assert.notNull(bookCopy, "@找不到此书！");
        Utils.updateAutoSet(bookCopy, currentUserInfo.get().getUserName());
        Utils.copy(updateBookCopy, bookCopy);
        bookCopyRepository.save(bookCopy);
        BookCopy returnValue = new BookCopy();
        BeanUtils.copyProperties(bookCopy, returnValue);
        BookCopyLogComponent.CreateBookCopyLog createBookCopyLog = new BookCopyLogComponent.CreateBookCopyLog();
        createBookCopyLog.setMetaId(returnValue.getId());
        createBookCopyLog.setBookCopyState(updateBookCopy.getState());
        createBookCopyLog.setRemark(currentUserInfo.get().getUserName() + " 更新了书籍副本 " + returnValue.getLibNumber());
        bookCopyLogComponent.createBookCopyLog(createBookCopyLog);
        return returnValue;
    }

    @Override
    @Transactional
    public BookCopy createBookCopy(CreateBookCopy createBookCopy) throws AccessDeniedException {
        BookCopy bookCopy = Utils.createAutoSet(BookCopy.class, currentUserInfo.get().getUserName());
        Utils.copy(createBookCopy, bookCopy);
        bookCopyRepository.save(bookCopy);
        BookCopy returnValue = new BookCopy();
        BeanUtils.copyProperties(bookCopy, returnValue);
        BookCopyLogComponent.CreateBookCopyLog createBookCopyLog = new BookCopyLogComponent.CreateBookCopyLog();
        createBookCopyLog.setMetaId(returnValue.getId());
        createBookCopyLog.setBookCopyState(BookCopyState.在馆);
        createBookCopyLog.setRemark(currentUserInfo.get().getUserName() + " 创建了书籍副本 " + returnValue.getLibNumber());
        bookCopyLogComponent.createBookCopyLog(createBookCopyLog);
        return returnValue;
    }
}
